package deep.projects.newsapp.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.wuxinwudai.adlg.ProgressDialog;
import com.wuxinwudai.android.app.AppConfig;
import com.wuxinwudai.android.app.BaseFragment;
import com.wuxinwudai.android.util.ArrayUtils;
import com.wuxinwudai.android.util.ViewUtils;
import com.wuxinwudai.android.widget.DividerItemDecoration;
import com.wuxinwudai.android.widget.ExRecyclerViewAdapter;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import cn.bingoogolapple.refreshlayout.BGAStickinessRefreshViewHolder;
import deep.projects.newsapp.R;
import okhttp3.Call;
import okhttp3.Response;

/**
 *
 * @author 吾心无待 于2016年06月02日
 */
public abstract class BGARefreshLayoutFragment<TA extends ExRecyclerViewAdapter> extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate {
    @BindView(R.id.bga_refresh_layout) BGARefreshLayout mBGARefreshLayout;
    @BindView(R.id.recycler_view) RecyclerView mRecyclerView;
    protected TA mAdapter;
    protected int mPage = 1;
    protected int mTotal = 1000;
    @Override
    public void onBGARefreshLayoutBeginRefreshing(final BGARefreshLayout refreshLayout) {
        if (mPage * AppConfig.PAGE_SIZE >= mTotal && mTotal > 0){
            mBGARefreshLayout.endRefreshing();
            return;
        }
        ViewUtils.showLoadingDialog(getContext());
        Object[] pvalues = getPageItfParamValues();
        if (pvalues == null){
            pvalues = new Object[]{mPage};
        }else{
            pvalues = ArrayUtils.join(new Object[]{mPage},pvalues);
        }
        String fmt =  getPageItfFormat();
        i( "onBGARefreshLayoutBeginRefreshing: "+ fmt);
        i("Url : "+String.format(fmt,pvalues));
        OkHttpUtils.get()
                .url(String.format(fmt,pvalues))
                .build()
                .execute(new Callback<JSONObject>() {
                    @Override
                    public JSONObject parseNetworkResponse(Response response) throws Exception {
                        return new JSONObject(response.body().string());
                    }
                    @Override
                    public void onError(Call call, Exception e) {
                        i("on Error:"+e.getMessage());
                        mBGARefreshLayout.endRefreshing();
                        ViewUtils.dismissLoadingDialog();
                    }
                    @Override
                    public void onResponse(final JSONObject response) {
                        refresh(response);
                        mBGARefreshLayout.endRefreshing();
                        ViewUtils.dismissLoadingDialog();
                    }
                });
        mPage++;
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return true;
    }
    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_bga_refresh_layout;
    }

    @Override
    protected void initChildView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this,mContentView);
        mBGARefreshLayout.setDelegate(this);
        BGAStickinessRefreshViewHolder stickinessRefreshViewHolder = new BGAStickinessRefreshViewHolder(getContext(), true);
        stickinessRefreshViewHolder.setStickinessColor(R.color.bs_bg_danger);
        stickinessRefreshViewHolder.setRotateImage(R.mipmap.bga_refresh_stickiness);
        mBGARefreshLayout.setRefreshViewHolder(stickinessRefreshViewHolder);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext()));
        mAdapter = getAdapter(getContext());
        mRecyclerView.setAdapter(mAdapter);
        if (savedInstanceState != null){
            readInstanceState(savedInstanceState);
        }

    }

    /**
     * 获取 RecyclerView 的数据适配器
     * @param context 上下文对象
     * @return 数据适配器
     */
    public abstract TA getAdapter(Context context);

    /**
     * 刷新 RecyclerView
     * @param jsonObject 从网络获取的 JsonObject 数据
     */
    public abstract void refresh(JSONObject jsonObject);

    /**
     * 获取分页数据接口格式
     * @return 分页数据接口格式
     */
    public abstract String getPageItfFormat();

    /**
     * 获取分页数据接口的其他参数值
     * @return 获取分页数据接口格式的其他参数的值
     */
    public Object[] getPageItfParamValues(){
        return null;
    }

    /**
     * 是否读取状态，该方法可用于读取状态值并初始化视图
     * @param savedInstanceState 状态存储
     */
    public void readInstanceState(@Nullable Bundle savedInstanceState){

    }
}
